package com.yangyu.service;

import com.yangyu.currency.Constant;
import com.yangyu.mapper.CommentMapper;
import com.yangyu.mapper.UserMapper;
import com.yangyu.message.BaseRsp;
import com.yangyu.message.comment.CommentByBlog;
import com.yangyu.pojo.Comment;
import com.yangyu.util.SnowflakeIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @version V1.0
 * @Package com.yangyu.service
 * @date 2021/1/13 20:40
 */
@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加评论
     *
     * @param comment
     * @return
     */
    public BaseRsp addComment(Comment comment) {
        Long id = SnowflakeIdUtil.generateId();
        comment.setId(id);
        commentMapper.addComment(comment);
        CommentByBlog commentById = commentMapper.getCommentById(id);
        return new BaseRsp(commentById);
    }

    /**
     * 查询评论
     *
     * @param blogId
     * @return
     */
    public BaseRsp getCommentByBlogId(long blogId) {
        BaseRsp rsp = new BaseRsp();

        // 根据博客id查询一级评论
        List<CommentByBlog> comments = commentMapper.getCommentByBlogId(blogId);
        if (CollectionUtils.isEmpty(comments)) {
            rsp.setData(new ArrayList<CommentByBlog>(0));
            return rsp;
        }

        // 迭代查询一级评论下的子评论
        comments.forEach(comment -> {
            List<CommentByBlog> childComments = commentMapper.getChildComment(comment.getId());
            if (CollectionUtils.isEmpty(childComments)) {
                comment.setChildComments(new ArrayList<>(0));
                return;
            }
            childComments.forEach(childComment -> {
                if (Constant.Comment.THIRD_COMMENT.equals(childComment.getLevelFlag())) {
                    String username = userMapper.getUserNameById(childComment.getToUid());
                    childComment.setToUserName(username);
                }
            });
            comment.setChildComments(childComments);
        });
        rsp.setData(comments);
        return rsp;
    }

}
